/**
 * # 防抖
 */
function debounce(fun, delay) {
  return function (args) {
    let that = this;
    let _args = args;
    clearTimeout(fun.id);
    fun.id = setTimeout(function () {
      fun.call(that, _args);
    }, delay);
  };
}

/**
 * 获取当前元素的行高
 */
function getLineHeight(el) {
  const computedStyle = window.getComputedStyle(el);
  const lineHeight = computedStyle.getPropertyValue("line-height");
  // 经验值，避免未设置行高时，高度计算出错
  if (lineHeight === "normal") {
    el.style.lineHeight = 1.2;
    return parseFloat(computedStyle.getPropertyValue("font-size")) * 1.2;
  }
  return parseFloat(lineHeight);
}

/**
 * # 监听dom宽高变化
 * @param {HTMLElement} el 被监听的元素
 * @param {Function} callback 宽高变化后的回调
 */
function observerDom(el, callback) {
  let resizeObserver = new ResizeObserver((entries) => {
    const contentRect = entries[0].contentRect;
    callback({
      width: Math.round(contentRect.width),
      height: Math.round(contentRect.height),
    });
  });
  resizeObserver.observe(el);
  return resizeObserver;
}

export { getLineHeight, observerDom, debounce };
